package com.xiaoma.tpo.dao;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.object.SqlCall;
import org.springframework.stereotype.Repository;

import com.xiaoma.tpo.baseDao.BaseDaoImpl;
import com.xiaoma.tpo.baseDao.DefaultRowMapper;
import com.xiaoma.tpo.domain.User;
import com.xiaoma.tpo.dto.TeacherVo;
import com.xiaoma.tpo.utils.Pager;

@Repository
public class UserDao extends BaseDaoImpl<User>{

    private static final Logger LOG = LoggerFactory.getLogger(UserDao.class);
    
    public boolean duplicated(int id, String name) {
        String sqlCount = "select count(1) from user where id != ? and name = ?";
        int totalCount = jdbcTemplate.queryForInt(sqlCount, id, name);
        return totalCount > 0;
    }
    //登录用户的查询
	public Pager querPageListByDay(String day,Integer page,Integer rows) {
		Pager pager = new Pager();
		String sql ;
		if(day != null && day != ""){
			sql = "select count(*) from user where created_at >= '"+day+" 00:00:00' and created_at <= '"+day+" 23:59:59'";
		}else{
			sql = "select count(*) from user";
			
		}
		int totalCount = jdbcTemplate.queryForInt(sql);
		pager.setTotalCount(totalCount);
		int startNum ;
		if(page == null || page == 0){
			startNum = 0;
		}else{
			startNum = (page-1)*rows;
		}
		String sqlList;
		if(day != null && day != ""){
			sqlList = "select * from user where created_at >= '"+day+" 00:00:00' and created_at <= '"+day+" 23:59:59' order by created_at limit "+startNum+","+rows;
		}else{
			sqlList = "select * from user order by id limit "+startNum+","+rows;
		}
		List<Object> users = jdbcTemplate.query(sqlList, new DefaultRowMapper(User.class , this.getNameHandler()));
		pager.setList(users);
		return pager;
	}
	
	public TeacherVo findTeacherById(int teacherId) {
	    String sql = "select id, name, nickname, avatar, role, description, tag, created_at from user where id = ? and role = 2";
	    List<?> teachers = jdbcTemplate.query(sql, new DefaultRowMapper(TeacherVo.class , this.getNameHandler()), teacherId);
	    return teachers.size() > 0 ? (TeacherVo)teachers.get(0) : null;
	}

}
